#include "databaseconnection.h"
#include <QSqlDatabase>
#include <QSqlError>
#include <QUuid>
#include <QMap>

// Static member initialization
QMap<QString, QString> DatabaseConnection::m_driverMap = {
    {"QSQLITE", "SQLite"},
    {"QMYSQL", "MySQL"},
    {"QPSQL", "PostgreSQL"},
    {"QODBC", "ODBC"},
    {"QOCI", "Oracle"},
    {"QDB2", "DB2"},
    {"QIBASE", "Firebird"},
    {"QTDS", "Sybase"}
};

DatabaseConnection::DatabaseConnection(QObject *parent)
    : QObject(parent)
{
}

DatabaseConnection::~DatabaseConnection()
{
    if (m_database.isOpen()) {
        m_database.close();
    }
}

bool DatabaseConnection::connect(const QString &driver, const QString &host, const QString &database,
                                 const QString &username, const QString &password, int port)
{
    // Close any existing connection
    if (m_database.isOpen()) {
        m_database.close();
    }
    
    // Generate a unique connection name
    m_connectionName = QUuid::createUuid().toString();
    
    // Create database connection
    m_database = QSqlDatabase::addDatabase(driver, m_connectionName);
    m_database.setHostName(host);
    m_database.setDatabaseName(database);
    m_database.setUserName(username);
    m_database.setPassword(password);
    
    if (port != -1) {
        m_database.setPort(port);
    }
    
    return m_database.open();
}

void DatabaseConnection::disconnect()
{
    if (m_database.isOpen()) {
        m_database.close();
    }
    
    // Remove the database connection
    QSqlDatabase::removeDatabase(m_connectionName);
    m_connectionName.clear();
}

bool DatabaseConnection::isConnected() const
{
    return m_database.isOpen();
}

QSqlDatabase DatabaseConnection::database() const
{
    return m_database;
}

QString DatabaseConnection::connectionName() const
{
    return m_connectionName;
}

QStringList DatabaseConnection::supportedDrivers()
{
    return QSqlDatabase::drivers();
}